package com.kxr.literetrofit.network.translator;

import com.alibaba.fastjson.util.ParameterizedTypeImpl;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.kxr.literetrofit.network.baseresponse.BaseResponse;

import java.io.IOException;
import java.lang.reflect.Type;

import okhttp3.ResponseBody;

/**
 * Created by kongxr on 2019/3/19.
 * 通用数据格式转化类
 */
public class SimpleTranslator<T> implements IDataTranslator {

    private Class<T> aClass;
    public SimpleTranslator(){}

    public SimpleTranslator(Class<T> clazz) {
        aClass = clazz;
    }

    @Override
    public BaseResponse<T> translate(ResponseBody responseBody) throws IOException{
//        String testJson = "{\"code\":-1,\"message\":\"Cannot get Jedis connection; nested exception is redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool\",\"data\":\"\"}";
        Gson gson = new Gson();
        String originResult = responseBody.string();
//        String callBackData = originResult.substring(0, originResult.length() - 64);
        if (aClass == null){
            Type jsonType = new TypeToken<BaseResponse<String>>() {}.getType();
            return gson.fromJson(originResult, jsonType);
        }else {
            Type ty = new ParameterizedTypeImpl(new Class[]{aClass}, null, BaseResponse.class);
            return gson.fromJson(originResult, ty);
        }
    }
}
